package cn.e3mall.cart.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.e3mall.common.util.CookieUtils;
import cn.e3mall.common.util.E3Result;
import cn.e3mall.pojo.TbUser;
import cn.e3mall.sso.service.TokenService;

public class LoginInterceptor implements HandlerInterceptor {

	@Autowired
	private TokenService tokenService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
			//前处理，执行handler之前执行此方法
		//返回true，放行      false：拦截
		//首先，从cookie中取token，
		String token = CookieUtils.getCookieValue(request, "token");
		//1.如果没有token，未登录状态，直接放行
		if (StringUtils.isBlank(token)) {
			return true;
		}
		//2.取到token，调用sso服务，根据token取用户信息
		E3Result e3Result = tokenService.getUserByToken(token);
		//2.1 没有取到登陆信息，登陆过期，放行	
		if (e3Result.getStatus()!=200) {
			return true;
		}
		//3。取到登陆信息，登陆 状态
		TbUser user = (TbUser) e3Result.getData();
		//把用户信息放到request中，只要在controller中判断request中是否包涵user信息。放行
		request.setAttribute("user", user);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
			throws Exception {
		//handler执行之后，返回modelAndView对象之前
			
		
	}

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		//完成处理，返回modelAndView对象之后
		//可以在此处理异常

	}

}
